const {exec} = require("child_process");

//获取当前时间
const getCurrentTime = (emptyStr = false) => {
  let time = new Date();
  let year = time.getFullYear()
  let mm = time.getMonth() + 1
  mm = mm < 10 ? '0' + mm : mm
  let dd = time.getDate()
  dd = dd < 10 ? '0' + dd : dd
  let hh = time.getHours()
  let mf = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()
  let ss = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()
  let timeStr = `${year}-${mm}-${dd} ${hh}:${mf}:${ss}`
  if (emptyStr) timeStr = timeStr.replace(/./g, '=')
  return timeStr
}

//执行command命令
const execCommand = (command) => {
  return new Promise((resolve, reject) => {
    if (command.indexOf("cd ") != -1) {
      let dirPath = command.replace("cd ", "");//D:\WorkPlace\Git_Project
      try {
        process.chdir(dirPath);
        resolve({stdout: `进入目录【${process.cwd()}】成功！`})
      } catch (e) {
        reject("进入目录失败！")
      }
    } else {
      try {
        exec(command, (error, stdout, stderr) => {
          let result = {stdout, error, stderr}
          console.log("execCommand=====", result)
          if (stdout) resolve(result)
          if (error) reject(error)
        });
      } catch (e) {
        reject(e)
      }
    }
  })
}

//获取执行命令后的多条结果
const readResultLines = (result) => {
  return result.split("\n").filter(item => item.trim())
}

module.exports = {
  execCommand,
  getCurrentTime,
  readResultLines,
}
